package bupt.xixi.learning.context.support;

import bupt.xixi.learning.beans.BeansException;
import bupt.xixi.learning.beans.factory.ConfigurableListableBeanFactory;
import bupt.xixi.learning.beans.factory.config.BeanFactoryPostProcessor;
import bupt.xixi.learning.beans.factory.config.BeanPostProcessor;
import bupt.xixi.learning.beans.factory.support.DefaultListableBeanFactory;
import bupt.xixi.learning.context.ApplicationEvent;
import bupt.xixi.learning.context.ApplicationListener;
import bupt.xixi.learning.context.ConfigurableApplicationContext;
import bupt.xixi.learning.context.event.ApplicationEventMulticaster;
import bupt.xixi.learning.context.event.ContextCloseEvent;
import bupt.xixi.learning.context.event.ContextRefreshedEvent;
import bupt.xixi.learning.context.event.SimpleApplicationEventMulticaster;
import bupt.xixi.learning.core.io.DefaultResourceLoader;

import java.util.Map;

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";

    private ApplicationEventMulticaster multicaster = null;

    @Override
    public void refresh() throws BeansException {
        // 1. 创建beanFactory, 并加载 beanDefinition
        refreshBeanFactory();

        // 2. 获取 BeanFactory
        DefaultListableBeanFactory beanFactory = getBeanFactory();

        // 3. 添加ApplicationContextAwareProcessor, 让继承ApplicationContextAware的bean对象都能感知到所属的ApplicationContext
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

        // 4. 在bean实例化之前，执行BeanFactoryPostProcessor
        invokeBeanFactoryPostProcessors(beanFactory);

        // 5. 注册BeanPostProcessor, 因为before...方法需要执行在实例化之前
        registerBeanPostProcessor(beanFactory);

        // 6. 初始化事件发布器
        initApplicationEventMulticaster();

        // 7. 注册事件监听器
        registerListeners();

        // 8. 提前实例化单例bean的对象 todo: 未使用
        beanFactory.preInstantiateSingletons();

        // 9. 发布容器刷新完成事件
        finishRefresh();
    }

    private void finishRefresh() {
        publishEvent(new ContextRefreshedEvent(this));
    }

    protected abstract DefaultListableBeanFactory getBeanFactory();

    protected abstract void refreshBeanFactory();

    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    private void registerBeanPostProcessor(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }


    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return getBeanFactory().getBeansOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return getBeanFactory().getBean(name);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return getBeanFactory().getBean(name, requiredType);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return getBeanFactory().getBean(name, args);
    }

    @Override
    public void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    }

    @Override
    public void close() {
        // 发布容器关闭事件
        publishEvent(new ContextCloseEvent(this));

        // 注销单例
        getBeanFactory().destroySingletons();
    }

    @Override
    public void publishEvent(ApplicationEvent event) {
        multicaster.multicastEvent(event);
    }

    private void initApplicationEventMulticaster() {
        DefaultListableBeanFactory beanFactory = getBeanFactory();
        multicaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, multicaster);
    }

    private void registerListeners() {
        Map<String, ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class);
        applicationListeners.forEach((name, listener) -> {
            multicaster.addApplicationListener(listener);
        });
    }
}
